#ifndef SERVERSDB_H
#define SERVERSDB_H

#include "CoreFarmAPI.h"


//////////////////////////////////////////////
// Servers node and 'methods'/////////////////
//////////////////////////////////////////////
typedef struct ServerNode{
	char address[SERVER_ADDR_LENGTH];
	int ID;
	struct ServerNode *next;

} ServerNode;

ServerNode* serverNodeConstructor(){
	ServerNode *thisNode;
	thisNode = (ServerNode*)malloc(sizeof(ServerNode));
	assertMem(thisNode);

	(*thisNode).ID = 0;
	(*thisNode).next = NULL;
	return thisNode;
}
void serverNodeSetAdr(ServerNode *thisNode, char *adr){ strcpy(thisNode->address, adr); }
void serverNodeSetID(ServerNode *thisNode, int ID){ thisNode->ID = ID; }
void serverNodeSetNext(ServerNode *thisNode, ServerNode *next){ thisNode->next = next; }
char* serverNodeGetAdr(ServerNode *thisNode){ return thisNode->address; }
int serverNodeGetID(ServerNode *thisNode){ return thisNode->ID; }
ServerNode* serverNodeGetNext(ServerNode *thisNode){ return thisNode->next; }

/////////////////////////////////////////////////////
// Server Database list structure and 'methods'//////
/////////////////////////////////////////////////////
typedef struct ServersDB{
	int size;
	ServerNode *head;

} ServersDB;
ServersDB *servers_DB = NULL;

void serversDBConstructor(){
	servers_DB = (ServersDB*)malloc(sizeof(ServersDB));
	assertMem( servers_DB );

	servers_DB->size = 0;
	servers_DB->head = NULL;
}

void serversDBSetHead(ServerNode *head){ servers_DB->head = head; }
ServerNode* serversDBGetHead(){ return servers_DB->head; }
int serversDBGetSize(){ return(servers_DB->size); }
int serversDBIsEmpty(){ return (servers_DB->size==0); }

int seversDBExists(char *serv){
	ServerNode *currNode=NULL;

	if( servers_DB )
		currNode = servers_DB->head;
	while( currNode ){

		if ( !strcmp( currNode->address, serv) )
			return 1;
		currNode = currNode->next;
	}

	return 0;
}

void serversDBPush(char *addr, int ID){
	ServerNode *newServer = serverNodeConstructor();
	serverNodeSetID(newServer, ID);
	serverNodeSetAdr(newServer, addr);

	if( !servers_DB )
		serversDBConstructor();

	if( !serversDBIsEmpty() )
		newServer->next = servers_DB->head;
	servers_DB->head = newServer;
	servers_DB->size++;
}

void serversPrintAll(){
	ServerNode *currNode=NULL;
	
	if( servers_DB )
		currNode = servers_DB->head;
	while( currNode ){
		printf("ID: %d Adr: %s\n", currNode->ID, currNode->address);
		currNode = currNode->next;
	}
}

#endif